package mimipost.database;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import minipost.user.model.Administrator;

public class AdministratorSql extends Database {

	private static final long serialVersionUID = -4346707339805623805L;

	public AdministratorSql() {
		super();
	}
	
	/**
	 * Validate the user
	 * @param userLogin - the name of the user
	 * @param userPass - the password of the user
	 * @return the state of the user is validated
	 * @throws SQLException
	 */
	public boolean isValidatedUser(String userLogin, String userPass) throws SQLException {
		PreparedStatement statement = 
				connection.prepareStatement("SELECT * FROM users WHERE username = ? and password = ?");
		statement.setString(1, userLogin);
		statement.setString(2, userPass);
		
		ResultSet result = statement.executeQuery();
		boolean flag = result.next();
		statement.close();

		return flag;
	}
	
	/**
	 * 插入新的管理员用户
	 * @param admin 管理员用户
	 * @throws SQLException
	 */
	public void insert(Administrator admin) throws SQLException {
		PreparedStatement statement = 
				connection.prepareStatement("INSERT INTO users (username, password) " + "VALUES(?, ?)");
		statement.setString(1, admin.getUsername());
		statement.setString(2, admin.getPassword());
		
		statement.executeUpdate();
		statement.close();
		//connection.commit();
	}
	
	/**
	 * 修改密码
	 * @param admin 修改后的管理员用户
	 * @throws SQLException
	 */
	public void updatePassword(Administrator admin) throws SQLException {
		PreparedStatement statement = 
				connection.prepareStatement("UPDATA users SET password = ? WHERE username = ?");
		statement.setString(1, admin.getPassword());
		statement.setString(2, admin.getUsername());
		
		statement.executeUpdate();
		statement.close();
		//connection.commit();
	}
	
	/**
	 * 按照管理员用户名删除
	 * @param username 管理员用户名
	 * @throws SQLException
	 */
	public void deleteByUsername(String username) throws SQLException {
		PreparedStatement statement = 
				connection.prepareStatement("DELETE FROM users WHERE username = ?");
		statement.setString(1, username);

		statement.executeUpdate();
		statement.close();
		//connection.commit();
	}
}
